<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :data="depts" :props="defaultProps" :expand-on-click-node="false">
        <template v-slot="{ data }">
          <el-row type="flex" justify="space-between" align="middle" style="width:100%;height:40px">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
            </el-col>
            <el-col :span="4">
              <el-dropdown @command="handleCommand($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <add-dept ref="addDept" :show-dialog.sync="showDialog" :current-node="currentNode" @updateDepartment="getDpartment" />
  </div>
</template>
<script>
import { getDepartment, deleteDepartment } from '@/api/department'
import { transtoTreeData } from '@/utils/index'
import AddDept from './components/add-dept.vue'
export default {
  name: 'Department',
  components: { AddDept },
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showDialog: false,
      currentNode: null
    }
  },
  created() {
    this.getDpartment()
  },
  methods: {
    async getDpartment() {
      const res = await getDepartment()
      this.depts = transtoTreeData(res, 0)
    },
    handleCommand(command, id) {
      if (command === 'add') {
        this.showDialog = true
        this.currentNode = id
      } else if (command === 'edit') {
        this.showDialog = true
        this.currentNode = id
        // 注意这里 prpo是异步，而this.$refs.addDept.getCompanyDetail()是同步，所以同步先执行后，再执行异步
        // 此时this.currentNode = id由于后执行，prpo还没执行完
        this.$nextTick(() => {
          this.$refs.addDept.getCompanyDetail()
        })
      } else {
        this.$confirm('此操作将永久删除该部门, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await deleteDepartment(id)
          this.getDpartment()
          this.$message.success('删除成功')
        })
      }
    }
  }
}
</script>
<style scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
}
</style>
